package com.yadang.controller;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


@RestController
@RequestMapping("/dowloadfile/file")
public class DownloadController {

    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(HttpServletResponse response) throws IOException {
        // 获取要下载的文件
        File file = new File("D:\\1.xml");
        // 如果文件不存在，则返回404状态码
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        // 设置响应头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", file.getName());
        headers.setContentLength(file.length());
        // 将文件内容封装到InputStreamResource对象中
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        // 返回响应
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }
}
